package fnic.prehand.esagent.passitive_measure2;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.pool2.ObjectPool;
import org.apache.log4j.Logger;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.common.xcontent.json.JsonXContentGenerator;

import fnic.prehand.augment.Flow;
import fnic.prehand.esagent.IndexAgent;

public class PassitiveAgent extends IndexAgent{
	private static final Logger log = Logger.getLogger(PassitiveAgent.class);
	//被动
	private static final List<String> flowFieldNames;
	private static final List<String> augmentFieldNames;
	private volatile static int agent_atmotic = 0;
	private JsonXContentGenerator jsongenerator;
	private ByteArrayOutputStream outstream;
	private int agent_sequencenum;

	static{ 
        flowFieldNames = config.getPflowfieldname();
        augmentFieldNames = config.getPaugfieldname();
		if(flowFieldNames.size() != MakeAugment.getFlowFieldNum() || augmentFieldNames.size() != MakeAugment.getAugmentFieldNum()){
			throw new IllegalArgumentException("[p.redis.flow-augment.field] illegal!");
		}
	}
	
	public PassitiveAgent(String idx, String type) {
		super(idx, type);
		agent_sequencenum = agent_atmotic++;
		// TODO Auto-generated constructor stub
		outstream = new ByteArrayOutputStream();
		try {
			jsongenerator = (JsonXContentGenerator) jsoncontent.createGenerator(outstream);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage());
		}
	}

	@Override
	public int getAgentSequenceNum(){
		return agent_sequencenum;
	}
	
	@Override
	protected void dealBulkIndexRsp(BulkResponse response) {
		//打印失败, 暂时不需要处理
		if(response.hasFailures()){
			log.error("passitive agent["+agent_sequencenum+"] failed to execute" + response.buildFailureMessage());
		}
	}

	@Override
	protected String jsonAugment(Object flowcsv) {
		Flow flowdata = (Flow) flowcsv;
		
		String json;
		try {
			jsongenerator.writeStartObject();

			for(int i=0; i<flowdata.num_oldFlow.length; i++){
				jsongenerator.writeNumberField(flowFieldNames.get(i), flowdata.num_oldFlow[i]);
			}
			for(int i=0; i<flowdata.augFlow.length; i++){
				jsongenerator.writeStringField(augmentFieldNames.get(i), flowdata.augFlow[i]);
			}
			
			jsongenerator.writeEndObject();
			jsongenerator.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage());
		}
		
		json = outstream.toString();
		outstream.reset();
		return json;
	}

	public void setIndexName(String idxName){
		indexName = idxName;
	}
	
	public String getIndexName(){
		return this.indexName;
	}
}
